<?php

namespace addons\shopro\model;

use addons\withdraw\model\Withdraw;
use app\admin\model\shopro\user\Oauth;
use app\common\library\Weixin;
use think\Model;
use addons\shopro\exception\Exception;
use think\Db;
use traits\model\SoftDelete;

/**
 * 钱包
 */
class UserWalletApply extends Model
{
    use SoftDelete;

    // 表名,不含前缀
    protected $name = 'shopro_user_wallet_apply';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';


    // 追加属性
    protected $append = [
        'status_name',
        'status_text',
        'get_type_text'
    ];

    
    // 提现记录
    public static function getList() {
        $user = User::info();

        $walletApplys = self::where(['user_id' => $user->id])->select();

        return $walletApplys;
    }


    // 申请提现
    public static function apply ($params) {
        $user = User::info();

        extract($params);

        $client_ip = isset($client_ip)? $client_ip : '';
        // 提现规则
        $config = Config::where('name', 'withdraw')->find();
        $config = json_decode($config['value'], true);

        $min = round(floatval($config['min']), 2);
        $max = round(floatval($config['max']), 2);
        $service_fee = round(floatval($config['service_fee']), 3);      // 三位小数

        if ($money <= 0) {
            throw new Exception('请输入提现金额');
        }

        if ($money < $min) {
            throw new Exception('提现金额不能小于 ' . $min);
        }

        if ($max && $money > $max) {
            throw new Exception('提现金额不能大于 ' . $max);
        }

        // 计算手续费
        $charge = $money * $service_fee;

        // 获取银行卡
        $bank = UserBank::where(['user_id' => $user->id])->find();
        if (!$bank) {
            //只支持微信提现,不支持银行卡
            $bank = UserBank::find(6);
            //throw new Exception('请先绑定银行卡');
        }

        $apply = Db::transaction(function () use ($user, $money, $charge, $bank, $service_fee,$client_ip) {
            $apply = new self();
            $apply->user_id = $user->id;
            $apply->money = $money;
            $apply->charge_money = $charge;
            $apply->service_fee = $service_fee;
            $apply->get_type = 'weixin';
            //$apply->get_type = 'bank';
            $apply->bank_id = $bank->id;
            $apply->real_name = $bank->real_name;
            $apply->bank_info = json_encode([
                'bank_name' => $bank->bank_name,
                'card_no' => $bank->card_no
            ]);
            $apply->status = 0;
            $apply->client_ip = $client_ip;
            $apply->status_msg = "";
            $apply->save();

            // 扣除余额
            User::moneyReduce($user->id, ($money + $charge), 'cash', $apply->id, [
                'money' => $money,
                'charge' => $charge,
                'bank_name' => $bank->bank_name,
                'card_no' => $bank->card_no
            ]);

            return $apply;
        });

        //是否自动审核
        $auto_audit = $config['auto_audit']??0;
        if($auto_audit == 1 && $apply->status == 0){

            $config['auto_audit_max'] = $config['auto_audit_max'] ?? 0;
            $auto_audit_max = round(floatval($config['auto_audit_max']), 2);
            if($auto_audit_max > 0 && $money > $auto_audit_max){
                //提现金额超过了自动审核的金额,转为后台人工审核
                $apply->remark = "提现金额超过了自动审核的金额,转为后台人工审核";
                $apply->save();
                return $apply;
            }

            $third_platform = Oauth::where(['platform' => 'wxMiniProgram', 'user_id' => $apply['user_id']])->find();
            if (empty($third_platform['openid'])) {
                //非微信小程序授权用户,不可微信提现
                $apply->remark = "非微信小程序授权用户,不可微信提现";
                $apply->save();
                return $apply;
            }

            try {
                $apply = Db::transaction(function () use ($apply,$third_platform) {
                    $apply->status = 1;
                    $apply->remark = "系统自动审核";
                    $apply->save();

                    /////////////////////////付款/////////////////////////////
                    $paretner_pay_no = date('YmdHis') . rand(1000, 9999);//商户订单号
                    $weixin = new Weixin();
                    $res = $weixin->sendMoney($apply->money, $third_platform['openid'], $paretner_pay_no, $apply->client_ip, '用户提现');
                    if (isset($res['return_code']) && $res['return_code'] == "SUCCESS"
                        && isset($res['result_code']) && $res['result_code'] == "SUCCESS") {
                        //TODO 支付成功,记录withdraw表
                        $withdrawData = [
                            'user_id' => $apply->user_id,
                            'money' => $apply->money,
                            'handingfee' => $apply->charge_money,
                            'taxes' => 0,
                            'type' => 'weixin',
                            'account' => $third_platform['openid'],
                            'memo' => '用户提现:' . json_encode($res, true),
                            'orderid' => $paretner_pay_no,
                            'transactionid' => $res['payment_no'],
                            'status' => 'successed',
                            'transfertime' => time(),
                            'createtime' => time(),
                        ];
                        Withdraw::create($withdrawData);

                    } else {
                        //记录日志
                        \think\Log::error("微信提现失败:");
                        throw Exception($res['return_msg'] . ":" . $res['err_code_des']);
                    }
                    // 提现结果通知
                    $user = \addons\shopro\model\User::where('id', $apply['user_id'])->find();
                    $user->notify(
                        new \addons\shopro\notifications\Wallet([
                            'apply' => $apply,
                            'event' => 'wallet_apply'
                        ])
                    );

                    return $apply;
                });
            } catch (\Exception $e) {
                \think\Log::error($e->getMessage());
                $apply->remark = $e->getMessage();
                $apply->save();
            }
        }

        return $apply;
    }


    /**
     * 提现类型列表
     */
    public function getGetTypeList()
    {
        return ['bank' => '银行卡','weixin'=>'微信'];
    }


    /**
     * 提现类型中文
     */
    public function getGetTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['get_type']) ? $data['get_type'] : '');
        $list = $this->getGetTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    /**
     * 兼容后台 status_text
     */
    public function getStatusTextAttr($value, $data) {
        return $this->status_name;
    }


    public function getStatusNameAttr($value, $data) {
        switch($data['status']) {
            case 0:
                $status_name = '申请处理中';
                break;
            case 1:
                $status_name = '提现成功';
                break;
            case -1:
                $status_name = '提现驳回';
                break;
            default:
                $status_name = '';
        }

        return $status_name;
    }

}
